<template>
  <div class="container-wrapper">
    <div class="row-padding justify-center container-xxl container-row">
      <div class="wrapper">
        <div>
          <div class="user-info">
            <div class="info-group">
              <label for="email"><i class="fas fa-envelope"></i> 邮箱</label>
              <div class="input-container">
                <i class="fas fa-envelope"></i>
                <input
                    type="email"
                    id="email"
                    v-model="user.email"
                    :class="{'error-input': errors.email}"
                    :readonly="!isEditing"
                    placeholder="输入您的邮箱地址"
                >
              </div>
              <div class="error-message" v-if="errors.email">
                {{ errors.email }}
              </div>
            </div>

            <div class="info-group">
              <label for="first_name"><i class="fas fa-user"></i> 名字</label>
              <div class="input-container">
                <i class="fas fa-user"></i>
                <input
                    type="text"
                    id="first_name"
                    v-model="user.first_name"
                    :class="{'error-input': errors.first_name}"
                    :readonly="!isEditing"
                    placeholder="输入您的名字"
                    @input="updateCharCount('first_name')"
                >
                <div class="char-count" :style="{ color: user.first_name.length > 50 ? '#e74c3c' : '#6c757d' }">
                  {{ user.first_name.length }}/50
                </div>
              </div>
              <div class="error-message" v-if="errors.first_name">
                {{ errors.first_name }}
              </div>
            </div>

            <div class="info-group">
              <label for="last_name"><i class="fas fa-user"></i> 姓氏</label>
              <div class="input-container">
                <i class="fas fa-user"></i>
                <input
                    type="text"
                    id="last_name"
                    v-model="user.last_name"
                    :class="{'error-input': errors.last_name}"
                    :readonly="!isEditing"
                    placeholder="输入您的姓氏"
                    @input="updateCharCount('last_name')"
                >
                <div class="char-count" :style="{ color: user.last_name.length > 50 ? '#e74c3c' : '#6c757d' }">
                  {{ user.last_name.length }}/50
                </div>
              </div>
              <div class="error-message" v-if="errors.last_name">
                {{ errors.last_name }}
              </div>
            </div>

            <div class="info-group">
              <label for="mobile"><i class="fas fa-mobile-alt"></i> 手机 (美国)</label>
              <div class="input-container">
                <i class="fas fa-mobile-alt"></i>
                <input
                    type="text"
                    id="mobile"
                    v-model="user.mobile"
                    :class="{'error-input': errors.mobile}"
                    :readonly="!isEditing"
                    placeholder="例如: (123) 456-7890"
                    @input="formatPhoneNumber"
                >
              </div>
              <div class="error-message" v-if="errors.mobile">
                {{ errors.mobile }}
              </div>
            </div>

            <div class="info-group">
              <label for="address"><i class="fas fa-map-marker-alt"></i> 默认收货地址</label>
              <div class="input-container">
                <i class="fas fa-map-marker-alt"></i>
                <textarea
                    id="address"
                    v-model="user.address"
                    :class="{'error-input': errors.address}"
                    :readonly="!isEditing"
                    placeholder="输入您的收货地址"
                    rows="3"
                    @input="updateCharCount('address')"
                ></textarea>
                <div class="char-count" :style="{ color: user.address.length > 10 ? '#e74c3c' : '#6c757d' }">
                  {{ user.address.length }}/100
                </div>
              </div>
              <div class="error-message" v-if="errors.address">
                {{ errors.address }}
              </div>
            </div>
          </div>

          <div class="actions">
            <button
                v-if="!isEditing"
                class="btn btn-edit"
                @click="startEditing"
            >
              <i class="fas fa-edit"></i> 编辑信息
            </button>

            <template v-else>
              <button
                  class="btn btn-save"
                  @click="saveUserInfo"
                  :disabled="isSaving"
              >
                <span v-if="isSaving" class="loading-spinner"></span>
                <i v-else class="fas fa-save"></i>
                {{ isSaving ? '保存中...' : '保存修改' }}
              </button>

              <button
                  class="btn btn-cancel"
                  @click="cancelEditing"
                  :disabled="isSaving"
              >
                <i class="fas fa-times"></i> 取消
              </button>
            </template>
            <button
                class="btn btn-out"
                @click="outLogin"
            >
              <i class="fa-solid fa-right-from-bracket"></i>LOGOUT
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import {defineProps, defineEmits, defineExpose, onMounted, reactive, ref, watch} from 'vue'
import { userStore } from '@/store/user.ts';
import {useRouter} from "vue-router";
import {oauthUserInfo} from "../../api/oauth";
import {updateUserInfo, userInfo} from "../../api/userApi";
import { useQuasar } from 'quasar'

const $q = useQuasar()

const router = useRouter()
const userstore = userStore()

defineProps({})

const emit = defineEmits([])

defineExpose({})

const showLoading = () => {
  $q.loading.show()
}
showLoading()

// $q.loading.hide()
const hideLoading = () => {
  $q.loading.hide()
}

interface userInfoInterface {
  id: number
  email: string,
  first_name: string,
  last_name: string
  mobile: string,
  address?: string
}

// 初始用户数据
const originalUser = reactive({ ...userstore.$state.userInfo })

// 深度监听 userInfo 的变化
watch(() => userstore.$state.userInfo, (newVal) => {
  // 当 userInfo 变化时更新 originalUser
  Object.assign(originalUser, newVal)
  console.log('User info updated:', newVal)
}, { deep: true })

// 响应式用户数据
const user = reactive({ ...originalUser });


const setUser = (info: userInfoInterface) => {
  user.id = info.id
  user.email = info.email
  user.address = info.address
  user.first_name = info.first_name
  user.last_name = info.last_name
  user.mobile = info.mobile
}

// 添加回调处理（在页面创建时检查）
onMounted(() => {
  const url = window.location.href;
  console.log(url)
// 解析URL
  const urlObj = new URL(url);
  const hash = urlObj.hash.substring(1);
  const hashParts = hash.split('?');
  console.log(hashParts)
// 获取查询参数中的taskId todo 目前是#/的路由, 之后改成域名可能要改
  let oauthValue = null;
  console.log(oauthValue)
  if (hashParts.length > 1) {
    // 如果有查询参数部分
    const queryString = hashParts[1];
    // 使用URLSearchParams解析查询字符串
    const params = new URLSearchParams(queryString);
    oauthValue = params.get('oauth');
  }
  if (oauthValue) {
    console.log(userstore.userInfo.token, "++++++++++")
    // 获取用户信息
    oauthUserInfo().then((res) => {
      userstore.setToken(res.data.token)
      userstore.setUserInfo(res.data)
      setUser(res.data)
      hideLoading()
    })
  }else{
    if (userstore.userInfo.token && userstore.userInfo.token != "") {
      userInfo().then((res) => {
        console.log(res.data, 778899)
        userstore.setUserInfo(res.data)
        setUser(res.data)
        hideLoading()
      }).catch((err) => {
        hideLoading()
        router.push("/pc/Login")
      });
    }else{
      hideLoading()
      router.push("/pc/Login")
    }
  }
})

const outLogin = () => {
  userstore.outLogin()
  router.push("/pc/Login")
}

// 编辑状态
const isEditing = ref(false);
const isSaving = ref(false);

// 错误信息
const errors = reactive({
  email: '',
  first_name: '',
  last_name: '',
  mobile: '',
  address: ''
});

// 通知相关
const notificationType = ref('success'); // 'success' 或 'error'

// 开始编辑
const startEditing = () => {
  isEditing.value = true;
};

// 取消编辑
const cancelEditing = () => {
  // 重置为原始数据
  Object.assign(user, originalUser);
  clearErrors();
  isEditing.value = false;
};

// 清除所有错误
const clearErrors = () => {
  errors.email = '';
  errors.first_name = '';
  errors.last_name = '';
  errors.mobile = '';
  errors.address = ''
};

// 验证表单
const validateForm = () => {
  let isValid = true;
  clearErrors();

  // 邮箱验证
  if (!user.email) {
    errors.email = '邮箱不能为空';
    isValid = false;
  } else if (!validateEmail(user.email)) {
    errors.email = '请输入有效的邮箱地址';
    isValid = false;
  }

  // 名字验证
  if (!user.first_name) {
    errors.first_name = '名字不能为空';
    isValid = false;
  } else if (user.first_name.length > 50) {
    errors.first_name = '名字不能超过50个字符';
    isValid = false;
  }

  // 姓氏验证
  if (!user.last_name) {
    errors.last_name = '姓氏不能为空';
    isValid = false;
  } else if (user.last_name.length > 50) {
    errors.last_name = '姓氏不能超过50个字符';
    isValid = false;
  }

  // 手机号验证
  if (!user.mobile) {
    errors.mobile = '手机号不能为空';
    isValid = false;
  } else if (!validateUSPhone(user.mobile)) {
    errors.mobile = '请输入有效的美国手机号';
    isValid = false;
  }

  // 地址验证
  if (user.address.length > 100) {
    errors.address = '地址不能超过100个字符';
    isValid = false;
  }
  return isValid;
};

// 保存用户信息
const saveUserInfo = () => {
  if (!validateForm()) {
    showNotificationMessage('请修正表单中的错误', 'error');
    return;
  }

  isSaving.value = true;

  // 模拟API请求
  Object.assign(originalUser, { ...user });
  updateUserInfo(originalUser).then((res) => {
    isSaving.value = false;
    isEditing.value = false;
    userstore.setUserInfo(originalUser)
    showNotificationMessage('用户信息已成功更新！', 'success');
  }).catch((err) => {
    console.log(err)
  });
};

// 显示通知
const showNotificationMessage = (message, type = 'success') => {
  let color = ""
  let icon = ""
  if (type === 'success'){
    color = 'teal'
    icon = 'check'
  }else if (type === 'error'){
    color = 'red'
    icon = 'xmark'
  }else if (type === 'warning'){
    color = 'yellow'
    icon = 'circle-exclamation'
  }else{
    color = 'gray'
  }

  $q.notify({
    message,
    color,
    icon,
    position: 'top-right',
    timeout: Math.random() * 5000 + 3000
  })
};

// 手机号自动格式化功能
const formatPhoneNumber = () => {
  // 移除非数字字符
  let numbers = user.mobile.replace(/\D/g, '');

  // 限制最多10位数字
  if (numbers.length > 10) {
    numbers = numbers.substring(0, 10);
  }

  // 应用格式：(XXX) XXX-XXXX
  let formatted = '';
  if (numbers.length > 0) {
    formatted = '(' + numbers.substring(0, 3);
  }
  if (numbers.length > 3) {
    formatted += ') ' + numbers.substring(3, 6);
  }
  if (numbers.length > 6) {
    formatted += '-' + numbers.substring(6, 10);
  }

  // 更新模型值
  user.mobile = formatted;
};

// 邮箱验证函数
const validateEmail = (email) => {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
};

// 美国手机号验证函数
const validateUSPhone = (phone) => {
  const re = /^(\+\d{1,2}\s?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
  return re.test(phone);
};

// 更新字符计数（如果需要的话，这里主要是为了样式变化）
const updateCharCount = () => {
  // Vue的响应式系统会自动更新绑定到模板的值
};




</script>

<style scoped lang='less'>
.wrapper{
  padding: 0 50px;
  //.column{
  //  max-width: 480px;
  //}
  .q-input{
    padding-bottom: 15px;
  }
}
.q-btn--outline:hover{
  background: #5c8e61 !important;
}
:deep(.q-btn__content:hover){
  color: white !important;
}
.q-btn{
  width: 150px;
}
.user-info {
  display: flex;
  flex-direction: column;
  gap: 25px;
  margin-bottom: 30px;
}

.info-group {
  position: relative;
}

.info-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #2c3e50;
  font-size: 1rem;
  display: flex;
  align-items: center;
}

.info-group label i {
  margin-right: 10px;
  width: 24px;
  text-align: center;
  color: #4b6cb7;
}

.info-value {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  padding: 14px 15px;
  font-size: 1.05rem;
  color: #495057;
  min-height: 52px;
  display: flex;
  align-items: center;
  padding-left: 40px;
  position: relative;
  transition: all 0.3s ease;
}

.info-value i {
  position: absolute;
  left: 15px;
  color: #6c757d;
}

.input-container {
  position: relative;
}

.input-container i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #3498db;
  z-index: 2;
}

.info-group input {
  width: 100%;
  padding: 14px 15px 14px 45px;
  border: 2px solid #e0e6ed;
  border-radius: 12px;
  font-size: 1.05rem;
  transition: all 0.3s;
  background: #f8f9fa;
  font-family: 'Poppins', sans-serif;
}

.info-group input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
  background: white;
}

.info-group .error-message {
  color: #e74c3c;
  font-size: 0.85rem;
  margin-top: 5px;
  height: 20px;
  padding-left: 10px;
  font-weight: 500;
}

.char-count {
  position: absolute;
  right: 15px;
  bottom: 15px;
  font-size: 0.8rem;
  color: #6c757d;
  background: rgba(255, 255, 255, 0.7);
  padding: 2px 6px;
  border-radius: 10px;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
}

.btn {
  padding: 12px 30px;
  border: none;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  font-family: 'Poppins', sans-serif;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.btn-edit {
  background: linear-gradient(90deg, #3498db, #2980b9);
  color: white;
}

.btn-save {
  background: linear-gradient(90deg, #27ae60, #219653);
  color: white;
}

.btn-cancel {
  background: linear-gradient(90deg, #e74c3c, #c0392b);
  color: white;
}

.btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
}

.btn:active {
  transform: translateY(1px);
}

.btn-out {
  background: linear-gradient(90deg, @xtxColor, #2782ba);
  color: white;
}
.btn-out:hover {
  background: linear-gradient(90deg, @xtxColor, #2782ba);
  color: white;
}

.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 25px;
  border-radius: 12px;
  background: #27ae60;
  color: white;
  font-weight: 500;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 10px;
  opacity: 0;
  transform: translateX(120%);
  transition: all 0.4s ease;
}

.notification.show {
  opacity: 1;
  transform: translateX(0);
}

.notification.error {
  background: #e74c3c;
}

.instructions {
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 100%);
  border-left: 4px solid #3498db;
  padding: 15px;
  border-radius: 0 12px 12px 0;
  margin-bottom: 25px;
  font-size: 0.95rem;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.instructions h3 {
  margin-bottom: 8px;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.instructions ul {
  padding-left: 20px;
}

.instructions li {
  margin-bottom: 5px;
  color: #495057;
}

.form-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f4f8;
}

.form-header i {
  font-size: 28px;
  margin-right: 12px;
  color: #4b6cb7;
  background: linear-gradient(135deg, #4b6cb7, #182848);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.form-header h2 {
  color: #2c3e50;
  font-weight: 600;
  font-size: 1.8rem;
}

.decoration {
  position: absolute;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(107, 114, 255, 0.1) 0%, rgba(107, 114, 255, 0.01) 100%);
  top: -150px;
  right: -150px;
  z-index: 0;
}

.decoration-2 {
  position: absolute;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(52, 152, 219, 0.1) 0%, rgba(52, 152, 219, 0.01) 100%);
  bottom: -100px;
  left: -100px;
  z-index: 0;
}

.loading-spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top: 3px solid white;
  animation: spin 1s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .container {
    max-width: 95%;
  }

  .header {
    padding: 20px;
  }

  .content {
    padding: 30px 20px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    font-size: 2.8rem;
    margin-top: -60px;
  }

  .form-header h2 {
    font-size: 1.5rem;
  }

  .btn {
    padding: 10px 20px;
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .actions {
    flex-direction: column;
  }

  .btn {
    width: 100%;
    justify-content: center;
  }

  .header h1 {
    font-size: 1.8rem;
  }
}
/* 添加以下样式 */
.info-group textarea {
  width: 100%;
  padding: 14px 15px 14px 45px;
  border: 2px solid #e0e6ed;
  border-radius: 12px;
  font-size: 1.05rem;
  transition: all 0.3s;
  background: #f8f9fa;
  font-family: 'Poppins', sans-serif;
  resize: vertical; /* 允许垂直调整大小 */
  min-height: 100px;
  line-height: 1.5;
  white-space: pre-wrap; /* 保留换行符 */
}

.info-group textarea:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
  background: white;
}

.input-container {
  position: relative;
}

.input-container i {
  position: absolute;
  left: 15px;
  top: 18px; /* 调整图标位置以适应textarea */
  color: #3498db;
  z-index: 2;
}

.char-count {
  position: absolute;
  right: 15px;
  bottom: 15px;
  font-size: 0.8rem;
  color: #6c757d;
  background: rgba(255, 255, 255, 0.7);
  padding: 2px 6px;
  border-radius: 10px;
}
.input-container {
  position: relative;
}
.input-container i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #3498db;
  z-index: 2;
}
</style>